import json

from django.http import JsonResponse, HttpResponse, Http404
from django.shortcuts import render, redirect

# Create your views here.
from user import models


def login(request):
    if request.POST:
        # request.POST['q']
        # request.POST.get('q')
        name = request.POST['username']
        try:
            user = models.User.objects.get(username=name)
        except:
            # raise Http404("Question does not exist") # 抛异常
            return HttpResponse('Question does not exist')
        pwd = request.POST.get('password')
        if user.password == pwd:
            request.session['login'] = '已经登录'
            # return render(request, 'index.html', context={'username': name})
            # 重定向
            return redirect('../list/')
        else:
            return render(request, 'login.html')
    # get方法
    # print(request.GET['id'])
    return render(request, 'login.html')


# 返回JSON数据
def getjson(request):
    myjson = {
        'username': '周大哥',
        'password': '123456'
    }
    # return JsonResponse(myjson)
    return HttpResponse(json.dumps(myjson), content_type='application/json')
    # listdata = ["张三", "25", "19000347", "上呼吸道感染"]
    # return JsonResponse(listdata, safe=False)


# 接收JSON数据
def json2(request):
    result = json.loads(request.body)
    print(result['ID'])
    return render(request, 'login.html')


# 用户注册
def register(request):
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']
        img = request.FILES.get("img")
        user = models.User()
        # object.create()
        user.username = username
        user.password = password
        user.img = img
        # 数据保存
        user.save()
        return redirect("../login/")
    return render(request, 'register.html')


# 退出 清空Session
def logout(request):
    request.session.flush()
    return render(request, 'login.html')


# 登录成功后的用户列表
def list(request):
    # page 是当前页面数，切片是数据的位置，两者需要转换
    page = request.GET.get('page', 1)
    print(type(page))
    rows = request.GET.get('rows', 5)
    pos = (int(page) - 1) * int(rows)
    # 总记录数
    total = len(models.User.objects.all())
    # 总页数
    totalpage = int((total + int(rows) - 1) / int(rows))
    print(totalpage)
    print(pos)
    print(rows)
    users = models.User.objects.all().order_by('id')[pos:int(page) * int(rows)]
    return render(request, 'list.html', {'users': users, 'page': page,'totalpage': totalpage})


# 删除
def delete(request):
    id = request.GET.get("id", None)
    if id:
        models.User.objects.filter(id=id).delete()
    return redirect('../list/')
